//
//  YYESectionViewController.m
//  YuYingEDU
//
//  Created by 胡波 on 2018/1/3.
//  Copyright © 2018年 胡波. All rights reserved.
//

#import "YYESectionViewController.h"
#import "YYEChapterTableViewCell.h"
#import "YYEChapterModel.h"
#import "YYELittleChapterModel.h"

#import "YYEMyCourseViewController.h"
#import "ZFDownloadViewController.h"
#import "ZFDownloadManager.h"


@interface YYESectionViewController () <UITableViewDataSource,UITableViewDelegate>

{
    BOOL close[30];
}

@property (nonatomic,strong) YYEBaseTableView *tableView;
@property (nonatomic,strong) NSArray *closeArr;
@property (nonatomic,strong) NSArray *datas;
@property (nonatomic,strong) NSString *course;// 文件名
@property (nonatomic,strong) NSString *file_url;// 文件名


@property (nonatomic,assign) NSInteger clickSection;
@property (nonatomic,assign) NSInteger currentSection;
@property (nonatomic,assign) NSInteger clickPosition;
@property (nonatomic,assign) NSInteger currentPosition;


@end

@implementation YYESectionViewController

static NSString * chapterCell = @"chapterCell";
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    NSString *str = [InfoCache unarchiveObjectWithFile:@"course"];
    
    // 章节
    
    for (NSInteger i = 0; i < 30; i++) {
        close[i] = YES;
    }
    
    self.view.backgroundColor = [UIColor yellowColor];
    
    [self configUI];
    
    [self loadData];
    
    if ([LoginModel shareLogin].role.integerValue == 0) {

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(indexAction:) name:@"kIndexNotification" object:nil];

    }
    
}

- (void)indexAction:(NSNotification *)notification
{
    NSDictionary *dic = notification.userInfo;
    
    self.currentSection = [dic[@"currentSection"] integerValue];
    self.currentPosition = [dic[@"currentPosition"] integerValue];
    
    for (int i=0; i<self.datas.count; i++) {
        YYEChapterModel *cModel = self.datas[i];
        
        for (int j=0; j<cModel.children.count; j++) {
            YYELittleChapterModel *lModel = cModel.children[j];
            lModel.selected = NO;
            
        }
    }
    
    YYEChapterModel *cModel = self.datas[self.currentSection];
    YYELittleChapterModel *lModel = cModel.children[self.currentPosition];
    lModel.selected = YES;
    
    [self.tableView reloadData];
}



- (void)loadData {
    
    NSDictionary *dic = @{
                          @"uid":[LoginModel shareLogin].uid,
                          @"username":[LoginModel shareLogin].username,
                          @"token":[LoginModel shareLogin].token,
                          @"cid":self.cid,
                          };
    [AFNHelper post:GetLessonChapter parameters:dic success:^(id responseObject) {
        
        NSLog(@"%@",responseObject);
        if ([responseObject[@"status"] isEqual:@1]) {
            
            self.course = responseObject[@"course"];
//            self.file_url = responseObject[@"file_url"];
            [InfoCache archiveObject:self.course toFile:@"course"];

            self.datas = [YYEChapterModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
            [self.tableView reloadData];

            if ([self.mid isKindOfClass:[NSString class]]) {// 首次播放
                
                if (self.datas.count > 0) {
                    
                    // 当前章
                    self.currentSection = 0;
                    self.clickSection = self.currentSection;
                    
                    // 当前节的位置
                    self.currentPosition = 0;
                    self.clickPosition = self.currentPosition;
                    
                    YYEChapterModel *cModel = self.datas[0];
                    YYELittleChapterModel *lModel = cModel.children[0];
                    
                    
                    if ([self.delegate respondsToSelector:@selector(selectedVideoWithVideoID:clickSection:currentSection:clickPosition:currentPosition:data:)]) {
                        [self.delegate selectedVideoWithVideoID:lModel clickSection:self.clickSection currentSection:self.currentSection clickPosition:self.clickPosition currentPosition:self.currentPosition  data:self.datas];
                    }
                    
                    if ([LoginModel shareLogin].role.integerValue == 0) {
                        lModel.selected = YES;

                    }
                    
//                    lModel.selected = YES;
                    lModel.currutSelected = YES;
                    close[0] = !close[0];
                    NSIndexSet * index = [NSIndexSet indexSetWithIndex:0];
                    [self.tableView reloadSections:index withRowAnimation:UITableViewRowAnimationAutomatic];
                }
                

                
            }

            // 记录播放
            for (int i=0; i<self.datas.count; i++) {
                YYEChapterModel *cModel = self.datas[i];
                cModel.section = i;

                for (int j=0; j<cModel.children.count; j++) {
                    YYELittleChapterModel *lModel = cModel.children[j];
                    
                    lModel.section = i;
                    lModel.position = j;
                    

                    // 最新进度
                    if (self.mid.integerValue == lModel.id.integerValue) {
                        
                        // 当前章
                        self.currentSection = lModel.section;
                        self.clickSection = self.currentSection;
                        
                        // 当前节的位置
                        self.currentPosition = lModel.position;
                        self.clickPosition = self.currentPosition;
                        
                        if ([LoginModel shareLogin].role.integerValue == 0) {
                            lModel.selected = YES;
                            
                        }
                    }

                    // 返回再进来进度
                    if (self.mid2.integerValue == lModel.id.integerValue) {
                        
                        
                        if ([self.delegate respondsToSelector:@selector(selectedVideoWithVideoID:clickSection:currentSection:clickPosition:currentPosition:data:)]) {
                            [self.delegate selectedVideoWithVideoID:lModel clickSection:lModel.section currentSection:self.currentSection clickPosition:lModel.position currentPosition:self.clickPosition  data:self.datas];
                        }
                        
                        lModel.currutSelected = YES;
                        
                        close[i] = !close[i];
                        NSIndexSet * index = [NSIndexSet indexSetWithIndex:i];
                        [self.tableView reloadSections:index withRowAnimation:UITableViewRowAnimationAutomatic];
                        
                    }
                    
                }
            }
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.tableView reloadData];

            });
        }
        
    } faliure:^(id error) {
        
        NSLog(@"请求失败");
        
    }];
    
}

- (void)configUI {
    
//    LoginModel *model = [LoginModel shareLogin];
    [self.view addSubview:self.tableView];
    if ([LoginModel shareLogin].role.integerValue == 1||
        [LoginModel shareLogin].token.length == 0) {
        self.tableView.tableHeaderView = nil;
        UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10)];
        headerView.backgroundColor = GeneralBackColor;
        self.tableView.tableHeaderView = headerView;
    }
    else {
        self.tableView.tableHeaderView = [self headerView];

    }
    self.tableView.backgroundColor = GeneralBackColor;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.tableView registerClass:[YYEChapterTableViewCell class] forCellReuseIdentifier:chapterCell];
    
    [self.tableView makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(UIEdgeInsetsZero);
    }];
    
}

- (UIView *)headerView {
    
    UIView *contentView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 56)];
    contentView.backgroundColor = GeneralBackColor;
    
    UIButton *downLoadBtn = [[UIButton alloc]init];
    [downLoadBtn setTitle:@"下载课件" forState:UIControlStateNormal];
    [downLoadBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    downLoadBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [downLoadBtn setBackgroundColor:[UIColor whiteColor]];
    [downLoadBtn setImage:[UIImage imageNamed:@"download"] forState:UIControlStateNormal];
    [contentView addSubview:downLoadBtn];
    [downLoadBtn addTarget:self action:@selector(downAction) forControlEvents:UIControlEventTouchUpInside];
    
    [downLoadBtn makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(UIEdgeInsetsMake(8, 8, 8, 8));
    }];
    
    return contentView;
    
}

- (void)downAction
{
    if (self.course) {
        
//        NSString *url = [NSString stringWithFormat:@"%@%@&%@",Download,self.cid,@"q31313.xlsx"];
        NSString *url = [NSString stringWithFormat:@"%@%@",Download,self.cid];

        if ([[ZFDownloadManager sharedInstance] isFileDownloadingForUrl:url withProgressBlock:^(CGFloat progress, NSString *speed, NSString *remainingTime, NSString *writtenSize, NSString *totalSize) {
            
        }]) {
            
            [self.view makeToast:@"已加入下载列表!"];
//            return;
        }
        else if ([[ZFDownloadManager sharedInstance] isCompletion:url]) {
            //已经下载
            
            [self.view makeToast:@"该文件已下载完成!"];
        }
        else {
            
            [[ZFDownloadManager sharedInstance] download:url progress:^(CGFloat progress, NSString *speed, NSString *remainingTime, NSString *writtenSize, NSString *totalSize) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                });
            } state:^(DownloadState state) {}];
        }

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            YYEMyCourseViewController *vc = [[YYEMyCourseViewController alloc]init];
            vc.index = 3;
            [self.navigationController pushViewController:vc animated:YES];
        });

    }
    


    
}

- (YYEBaseTableView *)tableView {
    
    if (!_tableView) {
        _tableView = [[YYEBaseTableView alloc]initwithDelegate:self];
    }
    return _tableView;
    
}

- (NSArray *)datas {
    
    if (!_datas) {
        _datas = [NSMutableArray array];
    }
    return _datas;
    
}

#pragma mark -- UITableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.datas.count;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (close[section]) {
        return 0.01;
    }
    return [self.datas[section] children].count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    YYEChapterTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:chapterCell];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    YYEChapterModel *model = self.datas[indexPath.section];

    YYELittleChapterModel *lModel = [self.datas[indexPath.section] children][indexPath.row];

    cell.model = lModel;

    if (model.section <= self.currentSection) {
        
        if (model.section == self.currentSection) {
            
            if (lModel.position <= self.currentPosition) {
                
                cell.userInteractionEnabled = YES;
                
                // "type": 2, // 1是习题 2是考试
                if (lModel.type.integerValue == 1) {
                    
                    cell.examIV.image = [UIImage imageNamed:@"xiti"];// noplay

                }
                else {
                    cell.examIV.image = [UIImage imageNamed:@"exam"];// noplay

                }
                
                if (lModel.currutSelected) {
                    cell.nameLabel.textColor = [UIColor purpleColor];
                    cell.timeLabel.textColor = [UIColor purpleColor];

                }
                else {
                    cell.nameLabel.textColor = [UIColor blackColor];
                    cell.timeLabel.textColor = [UIColor blackColor];

                }

            }
            else {
                cell.nameLabel.textColor = [UIColor colorWithHexString:@"#999999"];
                cell.timeLabel.textColor = [UIColor colorWithHexString:@"#999999"];
                cell.userInteractionEnabled = NO;
                
                // "type": 2, // 1是习题 2是考试
                if (lModel.type.integerValue == 1) {
                    
                    cell.examIV.image = [UIImage imageNamed:@"xiti2"];// noplay

                }
                else {
                    cell.examIV.image = [UIImage imageNamed:@"img_xiti_gray"];// noplay

                }

            }
            
        }
        else {
            cell.userInteractionEnabled = YES;
            // "type": 2, // 1是习题 2是考试
            if (lModel.type.integerValue == 1) {
                
                cell.examIV.image = [UIImage imageNamed:@"xiti"];// noplay

            }
            else {
                cell.examIV.image = [UIImage imageNamed:@"exam"];// noplay
                
            }
            if (lModel.currutSelected) {
                cell.nameLabel.textColor = [UIColor purpleColor];
                cell.timeLabel.textColor = [UIColor purpleColor];
                
            }
            else {
                cell.nameLabel.textColor = [UIColor blackColor];
                cell.timeLabel.textColor = [UIColor blackColor];
                
            }
        }


    }
    else {
        cell.nameLabel.textColor = [UIColor colorWithHexString:@"#999999"];
        cell.timeLabel.textColor = [UIColor colorWithHexString:@"#999999"];
        cell.userInteractionEnabled = NO;
        
        // "type": 2, // 1是习题 2是考试
        if (lModel.type.integerValue == 1) {
            
            cell.examIV.image = [UIImage imageNamed:@"xiti2"];// noplay

        }
        else {
            cell.examIV.image = [UIImage imageNamed:@"img_xiti_gray"];// noplay
            
        }
    }

    if (self.isBuy.integerValue == 0) {
        
        cell.nameLabel.textColor = [UIColor colorWithHexString:@"#999999"];
        cell.timeLabel.textColor = [UIColor colorWithHexString:@"#999999"];
        cell.userInteractionEnabled = NO;
        
        // "type": 2, // 1是习题 2是考试
        if (lModel.type.integerValue == 1) {
            
            cell.examIV.image = [UIImage imageNamed:@"xiti2"];// noplay

        }
        else {
            cell.examIV.image = [UIImage imageNamed:@"img_xiti_gray"];// noplay
            
        }
    }
    else {
        if ([LoginModel shareLogin].role.integerValue == 1) {
            
            if (self.isBuy.integerValue == 1) {
                
                // "type": 2, // 1是习题 2是考试
                if (lModel.type.integerValue == 1) {
                    
                    cell.examIV.image = [UIImage imageNamed:@"xiti"];// noplay

                }
                else {
                    cell.examIV.image = [UIImage imageNamed:@"exam"];// noplay
                    
                }
                
                if (self.mark == 1) {
                    cell.userInteractionEnabled = NO;

                }
                else {
                    cell.userInteractionEnabled = YES;

                }
                
                if (lModel.currutSelected) {
                    cell.nameLabel.textColor = [UIColor purpleColor];
                    cell.timeLabel.textColor = [UIColor purpleColor];
                    
                }
                else {
                    cell.nameLabel.textColor = [UIColor blackColor];
                    cell.timeLabel.textColor = [UIColor blackColor];
                    
                }
                
            }
            

        }

    }
    
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 30;
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    YYEChapterModel *model = self.datas[section];
    
    UIView *contentView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30)];
    contentView.backgroundColor = GeneralBackColor;
    
    UIControl *backV = [[UIControl alloc]init];
    backV.backgroundColor = [UIColor whiteColor];
    [backV addTarget:self action:@selector(sectionClicked:) forControlEvents:UIControlEventTouchUpInside];
    backV.tag = 1000 + section;
    [contentView addSubview:backV];
    
    UIImageView *leftIV = [[UIImageView alloc]init];
    [contentView addSubview:leftIV];
    
    
    UIView *topLine = [[UIView alloc]init];
    topLine.backgroundColor = GeneralBlueColor;
    [contentView addSubview:topLine];
    
    UIView *bottomLine = [[UIView alloc]init];
    bottomLine.backgroundColor = GeneralBlueColor;
    [contentView addSubview:bottomLine];
    
    UILabel *nameLabel = [[UILabel alloc]init];
    nameLabel.font = [UIFont systemFontOfSize:14];
    nameLabel.text = [NSString stringWithFormat:@"%@ %@",[self.datas[section] title],[self.datas[section] name]];
    [contentView addSubview:nameLabel];

    NSInteger time = 0;
    for (NSInteger i = 0; i < [self.datas[section] children].count; i++) {
        time += [[self.datas[section] children][i] videoTime].integerValue;
    }
    
    UILabel *timeLabel = [[UILabel alloc]init];
    timeLabel.textColor = [UIColor blackColor];
    timeLabel.font = [UIFont systemFontOfSize:13];
    timeLabel.textAlignment = NSTextAlignmentRight;
    [contentView addSubview:timeLabel];
    
    if (time < 60) {
        timeLabel.text = @"小于1分钟";
        
    }
    else {
        timeLabel.text = [NSString stringWithFormat:@"%@分钟",@(time / 60).stringValue];
        
    }
    
    if (model.section < self.currentSection) {
        leftIV.image = [UIImage imageNamed:@"play"];

    }
    else {
        leftIV.image = [UIImage imageNamed:@"yuan"];


    }
    
    if (model.section <= self.currentSection) {
        nameLabel.textColor = [UIColor blackColor];
        timeLabel.textColor = [UIColor blackColor];
//        backV.userInteractionEnabled = YES;
    }
    else {
        nameLabel.textColor = [UIColor colorWithHexString:@"#999999"];
        timeLabel.textColor = [UIColor colorWithHexString:@"#999999"];
//        backV.userInteractionEnabled = NO;
        
    }
    
    if (self.isBuy.integerValue == 0) {
        leftIV.image = [UIImage imageNamed:@"yuan"];
        nameLabel.textColor = [UIColor colorWithHexString:@"#999999"];
        timeLabel.textColor = [UIColor colorWithHexString:@"#999999"];
        
    }
    if ([LoginModel shareLogin].role.integerValue == 1) {
        
        if (self.isBuy.integerValue == 1) {
            nameLabel.textColor = [UIColor blackColor];
            timeLabel.textColor = [UIColor blackColor];
        }
        
    }
    
    [backV makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(UIEdgeInsetsMake(0, 8, 0, 8));
    }];
    
    [leftIV makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(backV.left).offset(23);
        make.centerY.equalTo(backV.centerY);
        make.size.equalTo(CGSizeMake(11, 11));
    }];
    
    [topLine makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(backV.left).offset(28);
        make.top.equalTo(backV.top);
        make.bottom.equalTo(leftIV.top);
        make.width.equalTo(1);
    }];
    
    [bottomLine makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(backV.left).offset(28);
        make.bottom.equalTo(backV.bottom);
        make.top.equalTo(leftIV.bottom);
        make.width.equalTo(1);
    }];
    
    [nameLabel makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(leftIV.right).offset(23);
        make.centerY.equalTo(backV.centerY);
//        make.right.equalTo(backV.centerX);
    }];
    
    [timeLabel makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(backV.right).offset(-13);
        make.centerY.equalTo(backV.centerY);
    }];
    
    if (section == 0) {
        topLine.hidden = YES;
    }
    else {
        topLine.hidden = NO;

    }

    if (section == self.datas.count-1 && close[section]) {
        bottomLine.hidden = YES;
    }
    else {
        bottomLine.hidden = NO;
        
    }

    return contentView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 44;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    for (int i=0; i<self.datas.count; i++) {
        YYEChapterModel *cModel = self.datas[i];
        
        for (int j=0; j<cModel.children.count; j++) {
            YYELittleChapterModel *lModel = cModel.children[j];
            lModel.currutSelected = NO;
            
        }
    }
    
    YYELittleChapterModel *model = [self.datas[indexPath.section] children][indexPath.row];
    

    model.currutSelected = YES;
    [self.tableView reloadData];
    
    if ([self.delegate respondsToSelector:@selector(selectedVideoWithVideoID:clickSection:currentSection:clickPosition:currentPosition:data:)]) {
        [self.delegate selectedVideoWithVideoID:model clickSection:model.section currentSection:self.currentSection clickPosition:model.position currentPosition:self.currentPosition data:self.datas];
    }
    
}

- (void)sectionClicked:(UIControl *)view {
    
    NSInteger i = view.tag - 1000;
    close[i] = !close[i];
    
    NSIndexSet * index = [NSIndexSet indexSetWithIndex:i];
    [self.tableView reloadSections:index withRowAnimation:UITableViewRowAnimationAutomatic];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
